﻿

namespace Comm100.Framework.Infrastructure
{
    using System;
    using System.Data;
    using Comm100.Domain.Uow;
    using Microsoft.EntityFrameworkCore;
    using Microsoft.EntityFrameworkCore.Storage;


    public class EFUnitOfWork : IUnitOfWork
    {
        private IDbContextTransaction _transaction ;
        private BaseDBContext _dbContext;

        public IsolationLevel IsolationLevel { get; set; }

        public EFUnitOfWork(BaseDBContext dbContext, IsolationLevel level)
        {
            this.IsolationLevel = level;
            _transaction = dbContext.Database.BeginTransaction(level);
            _dbContext = dbContext;

            var databaseName = dbContext.Tenant.DatabaseName;

            ChangeDatabase(databaseName);
        }

        public event EventHandler Disposed;
        public void Complete()
        {
           _transaction.Commit();
        }

        public void Dispose()
        {
            _transaction.Dispose();
            Disposed(this, null);
        }

        private void ChangeDatabase(string databaseName)
        {
            var connection = _dbContext.Database.GetDbConnection();
            if (connection.State.HasFlag(ConnectionState.Open))
            {
                connection.ChangeDatabase(databaseName);
            }
            else
            {
                connection.Open();
                connection.ChangeDatabase(databaseName);
            }
        }
    }
}
